/** 教程链接：
 * https://dart.cn/language/#async
 */
// Dart 异步编程示例：async/await、Future、Stream

import 'dart:async'; // 提供 Future 和 Stream 支持
import 'dart:io';    // 提供文件操作

// 模拟一秒延迟
const oneSecond = Duration(seconds: 1);

// 异步函数：延迟后打印消息
Future<void> printWithDelay(String message) async {
  await Future.delayed(oneSecond);
  print(message);
}

// 异步函数：为多个对象创建描述文件
Future<void> createDescriptions(Iterable<String> objects) async {
  for (final object in objects) {
    try {
      final file = File('$object.txt');
      if (await file.exists()) {
        final modified = await file.lastModified();
        print('File for $object already exists. Modified: $modified');
        continue;
      }
      await file.create();
      await file.writeAsString('Start describing $object in this file.');
      print('Created description file for $object.');
    } on IOException catch (e) {
      print('Cannot create description for $object: $e');
    }
  }
}

// 普通类：Spacecraft
class Spacecraft {
  final String name;
  Spacecraft(this.name);
}

// 异步生成器：返回飞越的报告流（Stream）
Stream<String> report(Spacecraft craft, Iterable<String> objects) async* {
  for (final object in objects) {
    await Future.delayed(oneSecond);
    yield '${craft.name} flies by $object';
  }
}

Future<void> main() async {
  await printWithDelay('Mission starting...');

  final objects = ['Mars', 'Jupiter', 'Saturn'];
  final spacecraft = Spacecraft('Voyager I');

  await createDescriptions(objects);

  print('\nFlight report:');
  await for (final msg in report(spacecraft, objects)) {
    print(msg);
  }
}
